package com.itxiao.filter;

import com.alibaba.fastjson.JSON;

import com.itxiao.annotation.Token;
import com.itxiao.config.RedisKeyConfig;
import com.itxiao.config.SystemConfig;
import com.itxiao.pojo.vo.R;
import com.itxiao.service.SpuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CheckTokenInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate template;

    private static final Logger log = LoggerFactory.getLogger(CheckTokenInterceptor.class);;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.校验请求的控制层映射方法是否包含Token注解
        //1.验证当前的请求是否为映射方法
        if (handler instanceof HandlerMethod) {
            //2.强制转换
            HandlerMethod method = (HandlerMethod) handler;
            //3.验证是否包含Token注解
            if (method.hasMethodAnnotation(Token.class)) {
                //4.获取令牌
                String token = request.getHeader(SystemConfig.HEADER_TOKEN);
                // ✅ 重点：如果 token 为空，返回 401
                if (token == null || token.trim().isEmpty()) {
                    log.error("请求 {} 缺少 Token，请求路径: {}", request.getMethod(), request.getRequestURI());
                    return respondUnauthorized(response, "缺少令牌，请登录");
                }

                // 4. 验证 Redis 中是否存在该 token
                String key = RedisKeyConfig.AUTH_LOGIN_TOKEN + token;
                if (!template.hasKey(key)) {
                    log.error("Token 无效或已过期，token: {}, 请求路径: {}", token, request.getRequestURI());
                    return respondUnauthorized(response, "令牌无效或已过期，请重新登录");
                }

                // ✅ Token 有效，放行
                return true;
            }
        }
        return  true;
    }

            /**
             * 统一返回 401 响应
             */
            private boolean respondUnauthorized(HttpServletResponse response, String message) throws IOException, IOException {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println(JSON.toJSONString(R.fail(message)));
                return false; // 拦截请求
            }
}
